<template>
  <div class="order-analysis-container">
    <div class="page-header">
      <h2>订单分析</h2>
      <p>多维度分析订单数据，助力业务决策</p>
    </div>

    <!-- 时间范围选择 -->
    <div class="filter-container">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        @change="handleDateChange"
      />
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6" v-for="(stat, index) in statistics" :key="index">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
          <div class="stat-trend" :class="{ 'up': stat.trend > 0, 'down': stat.trend < 0 }">
            {{ Math.abs(stat.trend) }}% {{ stat.trend > 0 ? '增长' : '下降' }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 订单趋势图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>订单趋势</span>
              <el-radio-group v-model="trendType" size="small" @change="handleTrendTypeChange">
                <el-radio-button label="daily">日</el-radio-button>
                <el-radio-button label="weekly">周</el-radio-button>
                <el-radio-button label="monthly">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="orderTrendChart" id="orderTrendChart" class="chart"></div>
        </el-card>
      </el-col>

      <!-- 订单分布图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>订单分布</span>
              <el-radio-group v-model="distributionType" size="small" @change="handleDistributionTypeChange">
                <el-radio-button label="category">品类</el-radio-button>
                <el-radio-button label="region">地区</el-radio-button>
                <el-radio-button label="channel">渠道</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="orderDistributionChart" id="orderDistributionChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'OrderAnalysis',
  setup() {
    // 日期范围
    const dateRange = ref([])
    const dateShortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        }
      },
      {
        text: '最近一月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setMonth(start.getMonth() - 1)
          return [start, end]
        }
      },
      {
        text: '最近三月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setMonth(start.getMonth() - 3)
          return [start, end]
        }
      }
    ]

    // 统计数据
    const statistics = ref([
      { label: '总订单数', value: 0, trend: 0 },
      { label: '总金额', value: '¥0', trend: 0 },
      { label: '平均客单价', value: '¥0', trend: 0 },
      { label: '完成率', value: '0%', trend: 0 }
    ])

    // 图表相关
    const trendType = ref('daily')
    const distributionType = ref('category')
    const orderTrendChartRef = ref(null)
    const orderDistributionChartRef = ref(null)
    let orderTrendChart = null
    let orderDistributionChart = null

    // 初始化图表
    const initCharts = () => {
      if (orderTrendChartRef.value && orderDistributionChartRef.value) {
        orderTrendChart = echarts.init(orderTrendChartRef.value)
        orderDistributionChart = echarts.init(orderDistributionChartRef.value)
        
        window.addEventListener('resize', () => {
          orderTrendChart?.resize()
          orderDistributionChart?.resize()
        })
      }
    }

    // 更新趋势图表
    const updateTrendChart = async () => {
      try {
        const { data } = await axios.get('/api/admin/orders/trend', {
          params: {
            type: trendType.value,
            startDate: dateRange.value[0],
            endDate: dateRange.value[1]
          }
        })

        const option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['订单数', '订单金额']
          },
          xAxis: {
            type: 'category',
            data: data.dates
          },
          yAxis: [
            {
              type: 'value',
              name: '订单数',
              position: 'left'
            },
            {
              type: 'value',
              name: '订单金额',
              position: 'right',
              axisLabel: {
                formatter: '¥{value}'
              }
            }
          ],
          series: [
            {
              name: '订单数',
              type: 'line',
              data: data.counts
            },
            {
              name: '订单金额',
              type: 'line',
              yAxisIndex: 1,
              data: data.amounts
            }
          ]
        }

        orderTrendChart.setOption(option)
      } catch (error) {
        ElMessage.error('获取趋势数据失败')
      }
    }

    // 更新分布图表
    const updateDistributionChart = async () => {
      try {
        const { data } = await axios.get('/api/admin/orders/distribution', {
          params: {
            type: distributionType.value,
            startDate: dateRange.value[0],
            endDate: dateRange.value[1]
          }
        })

        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: data.map(item => item.name)
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
              data: data.map(item => ({
                name: item.name,
                value: item.value
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }

        orderDistributionChart.setOption(option)
      } catch (error) {
        ElMessage.error('获取分布数据失败')
      }
    }

    // 事件处理
    const handleDateChange = () => {
      updateTrendChart()
      updateDistributionChart()
    }

    const handleTrendTypeChange = () => {
      updateTrendChart()
    }

    const handleDistributionTypeChange = () => {
      updateDistributionChart()
    }

    // 生命周期钩子
    onMounted(() => {
      initCharts()
      // 设置默认时间范围为最近一月
      dateRange.value = dateShortcuts[1].value()
      handleDateChange()
    })

    return {
      dateRange,
      dateShortcuts,
      statistics,
      trendType,
      distributionType,
      orderTrendChartRef,
      orderDistributionChartRef,
      handleDateChange,
      handleTrendTypeChange,
      handleDistributionTypeChange
    }
  }
}
</script>

<style scoped>
.order-analysis-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 8px 0 0;
  color: #666;
}

.filter-container {
  margin-bottom: 24px;
}

.stat-cards {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.stat-label {
  margin-top: 8px;
  color: #666;
}

.stat-trend {
  margin-top: 8px;
  font-size: 12px;
}

.stat-trend.up {
  color: #67c23a;
}

.stat-trend.down {
  color: #f56c6c;
}

.chart-row {
  margin-bottom: 24px;
}

.chart-card {
  margin-bottom: 24px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 400px;
}
</style> 